"""知识库路由模块"""

from fastapi import APIRouter, HTTPException, Depends
from typing import List, Optional
from src.services.knowledge_base_service import (
    KnowledgeBaseItem,
    KnowledgeBaseQuery,
    SearchSuggestion,
    KnowledgeBaseService
)

def get_knowledge_base_service():
    return KnowledgeBaseService()
from src.utils.logging import get_logger

logger = get_logger(__name__)

router = APIRouter(prefix="/api/knowledge-base", tags=["知识库"])

@router.post("/items", response_model=KnowledgeBaseItem, summary="创建知识条目")
async def create_knowledge_item(
    item: KnowledgeBaseItem,
    service=Depends(get_knowledge_base_service)
):
    """
    创建新的知识库条目
    
    Args:
        item: 知识条目信息
        service: 知识库服务实例
        
    Returns:
        创建的知识条目
    """
    try:
        result = service.create_knowledge_item(item)
        return result
    except Exception as e:
        logger.error(f"创建知识条目失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/items/batch", response_model=List[KnowledgeBaseItem], summary="批量创建知识条目")
async def batch_create_knowledge_items(
    items: List[KnowledgeBaseItem],
    service=Depends(get_knowledge_base_service)
):
    """
    批量创建知识库条目
    
    Args:
        items: 知识条目列表
        service: 知识库服务实例
        
    Returns:
        创建的知识条目列表
    """
    try:
        result = service.batch_create_knowledge_items(items)
        return result
    except Exception as e:
        logger.error(f"批量创建知识条目失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/items/{item_id}", response_model=KnowledgeBaseItem, summary="获取知识条目")
async def get_knowledge_item(
    item_id: str,
    increment_view_count: bool = True,
    service=Depends(get_knowledge_base_service)
):
    """
    根据ID获取知识库条目
    
    Args:
        item_id: 知识条目ID
        increment_view_count: 是否增加查看次数
        service: 知识库服务实例
        
    Returns:
        知识条目信息
    """
    try:
        result = service.get_knowledge_item(item_id, increment_view_count)
        if not result:
            raise HTTPException(status_code=404, detail="知识条目未找到")
        return result
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取知识条目失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@router.put("/items/{item_id}", response_model=KnowledgeBaseItem, summary="更新知识条目")
async def update_knowledge_item(
    item_id: str,
    item: KnowledgeBaseItem,
    service=Depends(get_knowledge_base_service)
):
    """
    更新知识库条目
    
    Args:
        item_id: 知识条目ID
        item: 更新的知识条目信息
        service: 知识库服务实例
        
    Returns:
        更新后的知识条目
    """
    try:
        result = service.update_knowledge_item(item_id, item)
        return result
    except Exception as e:
        logger.error(f"更新知识条目失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@router.delete("/items/{item_id}", response_model=bool, summary="删除知识条目")
async def delete_knowledge_item(
    item_id: str,
    service=Depends(get_knowledge_base_service)
):
    """
    删除知识库条目
    
    Args:
        item_id: 知识条目ID
        service: 知识库服务实例
        
    Returns:
        删除是否成功
    """
    try:
        result = service.delete_knowledge_item(item_id)
        return result
    except Exception as e:
        logger.error(f"删除知识条目失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/search", response_model=List[KnowledgeBaseItem], summary="搜索知识条目")
async def search_knowledge_items(
    query: KnowledgeBaseQuery,
    service=Depends(get_knowledge_base_service)
):
    """
    搜索知识库条目
    
    Args:
        query: 搜索查询条件
        service: 知识库服务实例
        
    Returns:
        符合条件的知识条目列表
    """
    try:
        results = service.search_knowledge_items(query)
        return results
    except Exception as e:
        logger.error(f"搜索知识条目失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/semantic-search", response_model=List[KnowledgeBaseItem], summary="语义搜索知识条目")
async def semantic_search_knowledge_items(
    query: KnowledgeBaseQuery,
    service=Depends(get_knowledge_base_service)
):
    """
    基于语义的搜索知识库条目
    
    Args:
        query: 搜索查询条件，需要设置semantic_search为True
        service: 知识库服务实例
        
    Returns:
        语义相似的知识条目列表
    """
    try:
        # 强制启用语义搜索
        query.semantic_search = True
        results = service.search_knowledge_items(query)
        return results
    except Exception as e:
        logger.error(f"语义搜索知识条目失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/hybrid-search", response_model=List[KnowledgeBaseItem], summary="混合搜索知识条目")
async def hybrid_search_knowledge_items(
    query: KnowledgeBaseQuery,
    service=Depends(get_knowledge_base_service)
):
    """
    混合搜索知识库条目（关键词+语义）
    
    Args:
        query: 搜索查询条件，需要设置hybrid_search为True
        service: 知识库服务实例
        
    Returns:
        搜索结果列表
    """
    try:
        # 强制启用混合搜索
        query.hybrid_search = True
        results = service.search_knowledge_items(query)
        return results
    except Exception as e:
        logger.error(f"混合搜索知识条目失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/search-suggestions", response_model=List[SearchSuggestion], summary="获取搜索建议")
async def get_search_suggestions(
    prefix: str,
    limit: int = 10,
    service=Depends(get_knowledge_base_service)
):
    """
    获取搜索建议
    
    Args:
        prefix: 查询前缀
        limit: 返回建议数量限制
        service: 知识库服务实例
        
    Returns:
        搜索建议列表
    """
    try:
        suggestions = service.get_search_suggestions(prefix, limit)
        return suggestions
    except Exception as e:
        logger.error(f"获取搜索建议失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/items/{item_id}/related", response_model=List[KnowledgeBaseItem], summary="获取相关知识条目")
async def get_related_items(
    item_id: str,
    limit: int = 5,
    service=Depends(get_knowledge_base_service)
):
    """
    获取相关知识条目
    
    Args:
        item_id: 知识条目ID
        limit: 返回相关条目数量限制
        service: 知识库服务实例
        
    Returns:
        相关知识条目列表
    """
    try:
        related_items = service.get_related_items(item_id, limit)
        return related_items
    except Exception as e:
        logger.error(f"获取相关知识条目失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))